# encoding    : utf-8
# author      : 伦裕如
# project     : hrjt_-py1
# file        : sendEmailManage
# time        : 2024-06-24 上午9:49 

# 导入 smtplib 模块，用来发送邮件
import smtplib
# 导入 email 模块，用来编写发送邮件模板
from email.header import Header  # 构建头部信息
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText  # 发送 HTML或者纯文本


class SendEmailManage:
    def __init__(self, from_addr, password, smtp_server, port = 465):
        """
        初始化参数
        :param from_addr: 发信方邮箱地址
        :param password: 发信方邮箱授权码
        :param smtp_server: 发信方服务器
        :param port: 发信方服务器端口
        """
        self.from_addr = from_addr
        self.password = password
        self.smtp_server = smtp_server
        self.port = port

    def send_message(self, to_addr, subject, content, files = [], is_html = False):
        """
        发送邮件
        :param to_addr: 目标地址
        :param subject: 主题
        :param content: 内容
        :param files: 附件信息
        :return: 发送是否成功
        :param is_html: 邮件正文部分是否是HTML格式
        """
        # 邮件正文格式， plain - 纯文本
        subtype = 'html' if is_html else 'plain'
        # 邮箱正文，第一个参数为内容，第二个参数为格式。 第三个为编码方式
        msg = MIMEMultipart()

        # 邮件头信息
        msg['From'] = Header(self.from_addr)
        msg['To'] = Header(to_addr)
        msg['Subject'] = Header(subject)
        msg.attach(MIMEText(content, subtype, 'utf-8'))

        # 添加邮件附件信息
        for file in files:
            att = MIMEText(open(file, 'rb').read(), 'base64', 'utf-8')
            att["Content-Type"] = "application/octet-stream"
            att["Content-Disposition"] = 'attachment; filename="{}"'.format(file)
            msg.attach(att)
        # 发送邮件
        try:
            with smtplib.SMTP_SSL(self.smtp_server, self.port) as server:
                server.login(self.from_addr, self.password)
                server.sendmail(self.from_addr, to_addr, msg.as_string())
                print('发送成功')
                return True
        except Exception as e:
            print(f'发送失败：{e}')
            return False
